package com.chezai.client.activitys;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chezai.client.R;
import com.chezai.client.bean.ClassRecord;
import com.chezai.client.bean.CoachLoginRecord;
import com.chezai.client.bean.ImageInfo;
import com.chezai.client.bean.ReadIdCardBean;
import com.chezai.client.bean.TakePhotoEntity;
import com.chezai.client.bean.TerminalBaseInfo;
import com.chezai.client.bean.TerminalParameter;
import com.chezai.client.bean.TrainProjectEntity;
import com.chezai.client.bean.UserInfo;
import com.chezai.client.dao.manager.ClassRecordDaoManager;
import com.chezai.client.dao.manager.CoachLoginRecordDaoManager;
import com.chezai.client.dao.manager.TerminalBaseInfoDaoManager;
import com.chezai.client.dao.manager.TrainProjectEntityManager;
import com.chezai.client.dao.manager.UserInfoDaoManager;
import com.chezai.client.global.Const;
import com.chezai.client.global.DeviceFactory;
import com.chezai.client.global.NetConst;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.global.location.LocationMgr;
import com.chezai.client.server.TerminalSocketClientManager;
import com.chezai.client.server.TerminalSocketClientManager_8001;
import com.chezai.client.server.util.TransmissionMessageUtil;
import com.chezai.client.utils.AppManager;
import com.chezai.client.utils.BuildDataUtil;
import com.chezai.client.utils.DateUtil;
import com.chezai.client.utils.DeviceUtils;
import com.chezai.client.utils.DialogUtils;
import com.chezai.client.utils.LocationUtils;
import com.chezai.client.utils.PackageUtils;
import com.chezai.client.utils.PreferenceManager;
import com.chezai.client.utils.TerminalUtils;
import com.chezai.client.utils.ThreadManager;
import com.chezai.client.widget.ListDialog;
import com.chezai.client.widget.LoginTypeDialog;
import com.chezai.client.widget.NormalAlertDialog;
import com.chezai.client.widget.QRDialog;
import com.chezai.client.widget.ReadCardDialog;
import com.jx.driving.request.Terminal0x0100Request;
import com.jx.driving.request.Terminal0x0703Request;
import com.jx.driving.request.Terminal0x0900Request;
import com.jx.driving.response.AbstractResponse;
import com.jx.driving.response.Terminal0x8100Response;
import com.jx.driving.response.Terminal0x8702Response;
import com.jx.driving.response.Terminal0x8703Response;
import com.jx.driving.transmission.Terminal0x0101Transmission;
import com.jx.driving.transmission.Terminal0x0305Transmission;
import com.jx.driving.transmission.Terminal0x0306Transmission;
import com.jx.driving.transmission.Terminal0x0401Transmission;
import com.jx.driving.transmission.Terminal0x0402Transmission;
import com.jx.driving.transmission.Terminal0x8101Transmission;
import com.jx.driving.transmission.Terminal0x8401Transmission;
import com.jx.driving.transmission.Terminal0x8402Transmission;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.ref.SoftReference;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 科一二三四登录页
 * Created by likunyang on 2017/9/11.
 */

public class LoginActivity extends BaseActivity implements NormalAlertDialog.OnNormalAlertDialogListener, QRDialog.OnCountDownTimerFinishListener, ListDialog.OnItemClickListener, ReadCardDialog.OnInputOverListener, LoginTypeDialog.OnLoginTypeClickListener, DialogInterface.OnDismissListener {
    @BindView(R.id.btn_status)
    Button btnStatus;
    @BindView(R.id.btn_terminal_register)
    Button btnTerminalRegister;
    @BindView(R.id.btn_subject_two_three)
    Button btnSubjectTwoThree;
    @BindView(R.id.btn_subject_one)
    Button btnSubjectOne;
    @BindView(R.id.btn_subject_four)
    Button btnSubjectFour;
    @BindView(R.id.tv_login_company)
    TextView tvLoginCompany;
    @BindView(R.id.tv_login_version)
    TextView tvLoginVersion;
    private int mSubject;
    private short loginType;
    private QRDialog qrDialog;
    private TransmissionMessageUtil messageUtil;
    private UserInfo mCoachInfo; //当前登录教练
    private int sequence;
    private int subjectType;
    private boolean isIdCardReading;//是否正在读取身份证

    public static void openLogin(Activity form, Integer subjectType, Integer deviceBelong) {
        Intent intent = new Intent(form, LoginActivity.class);
        TerminalBaseInfo baseInfo = TerminalBaseInfoDaoManager.getInstance().getTerminalBaseInfo();


        intent.putExtra("subjectType", subjectType != null ? subjectType : baseInfo.getType());
        intent.putExtra("deviceBelong", deviceBelong != null ? deviceBelong : baseInfo.getDeviceBelong());
        form.startActivity(intent);
        form.finish();
    }


    @Override
    protected void onResume() {
        super.onResume();
        showOrHide();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    private void showOrHide() {
        boolean isRegister = PreferenceManager.isRegister();
        if (isRegister) {
            btnStatus.setVisibility(View.VISIBLE);
            btnTerminalRegister.setText("终端注销");
        } else {
            btnStatus.setVisibility(View.GONE);
            btnTerminalRegister.setText("终端注册");
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    /**
     * subjectType
     * 如果是课堂终端（Const.CLASS_TYPE),则显示科一/科四登录按钮
     * 如果是车载终端（Const.CAR_TYPE）,则显示科二/科三登录按钮
     */
    @Override
    public void initView(Bundle savedInstanceState) {
        subjectType = getIntent().getIntExtra("subjectType", 0);
        int deviceBelong = getIntent().getIntExtra("deviceBelong", -1);
        if (Const.CLASS_TYPE == subjectType) {//课堂终端
            btnSubjectTwoThree.setVisibility(View.GONE);
            btnSubjectOne.setVisibility(View.VISIBLE);
            btnSubjectFour.setVisibility(View.VISIBLE);
        } else if (Const.CAR_TYPE == subjectType || Const.SIMULATE_TYPE == subjectType) {//车载终端
            btnSubjectTwoThree.setVisibility(View.VISIBLE);
            btnSubjectOne.setVisibility(View.GONE);
            btnSubjectFour.setVisibility(View.GONE);
        }
        switch (deviceBelong) {
            case 0:
                tvLoginCompany.setText("技术支持：山西至诚希望科技有限公司");
                break;
            case 1:
                tvLoginCompany.setText("技术支持：北京一五八零互联网科技有限公司");
                break;
            default:
                tvLoginCompany.setText("");
                break;
        }
        tvLoginVersion.setText("版本 " + (NetConst.RELEASE_SERVER ? "V " : "Test_V ") + PackageUtils.getVersionName(new SoftReference<Context>(this)));

    }


    @Override
    public void initData() {
        LocationMgr.getInstance();
        messageUtil = new TransmissionMessageUtil();
        //设置703B Acc 关机时间
        DeviceFactory.hardware.setAccPowerTime(this, 3 * 60 * 1000);
        DeviceFactory.hardware.getPowerTime();
        switch (subjectType) {
            case Const.CLASS_TYPE:
                checkIsHasUnSignOutCoach();
                break;
            case Const.CAR_TYPE:
            case Const.SIMULATE_TYPE:
                checkIsHasNoFinishedTrain();
                break;
        }
        getShowUrl();

    }


    /**
     * harisucici
     * 获取推流地址
     */

    public void getShowUrl() {
        Logger.t(TAG).i("获取推流url");
        Callback.Cancelable cancelable = x.http().get(getUrlParams(), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Logger.t(TAG).i("检查推流url成功。");
                Log.e("harisucici","检查推流url成功"+result);

                if (result != null) {
                    //harisucici
                    if (!TextUtils.isEmpty(result)) {
                        Logger.t(TAG).i("最新推流url地址：" + result);
                        PreferenceManager.putString("SHOWURL", result);
                        String s = PreferenceManager.getString("SHOWURL", "");
                        String s1 = PreferenceManager.getString("SHOWURL", "");
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Logger.t(TAG).e("检查推流urlOnError。" + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Logger.t(TAG).i("检查推流url取消。");
            }

            @Override
            public void onFinished() {
                Logger.t(TAG).i("检查推流urlFinished");
            }
        });
    }

    private RequestParams getUrlParams() {
        TerminalBaseInfo terminalBaseInfo = TerminalBaseInfoDaoManager.getInstance().getTerminalBaseInfo();
        StringBuilder sb = new StringBuilder();
        sb.append(NetConst.GET_PUSH_URL);
        sb.append(terminalBaseInfo.getInscode() + "");
        sb.append("/");
        sb.append(terminalBaseInfo.getIdentification());
        Log.e("harisucici", "获取Url:" + sb.toString());
        RequestParams requestParams = new RequestParams(sb.toString());
        return requestParams;
    }

    /**
     * 查看科一、科四是否有未签退的教练
     */
    private void checkIsHasUnSignOutCoach() {
        CoachLoginRecord coachLoginRecord = CoachLoginRecordDaoManager.getInstance().findOneOrFourUnSignOutCoach();
        if (coachLoginRecord != null) {
            OneAndFourActivity.startOneAndFourActivity(this, coachLoginRecord.get_ID(), coachLoginRecord.getTeachSubject(), coachLoginRecord.getProjectCode(), coachLoginRecord.getProjectName());
            finish();
        }
    }

    /**
     * 查看科二、科三是否有未结束的训练
     * 如果此未结束的训练，与当前天非同一天，则不能继续训练。继续训练按钮置灰，只能结束教学
     */
    private void checkIsHasNoFinishedTrain() {
        List<ClassRecord> noFinishedTrain = ClassRecordDaoManager.getInstance().findUnFinishedTwoOrThreeTrain();
        if (noFinishedTrain != null) {
            boolean isGoOn = true;
            ClassRecord classRecord = noFinishedTrain.get(0);
            if (classRecord != null && !TextUtils.equals(classRecord.getCreateTime(), DateUtil.timestampStr(DateUtil.sf18))) {
                isGoOn = false;
            }
            boolean isReboot = PreferenceManager.getBoolean(Const.SP_IS_REBOOT, false);
            if (isReboot) {
                PreferenceManager.putBoolean(Const.SP_IS_REBOOT, false);
                TwoAndThreeActivity.unusualOpen(this, noFinishedTrain.get(0).get_ID(), false);
                finish();
            } else {
                DialogUtils.showDoubleButtonAlertDialog(this, "提示", "有未结束的培训", "结束训练", "继续训练", isGoOn, Const.DIALOG_HAS_UNFINISH_TAG, this);
            }
        }
    }

    @OnClick({R.id.btn_status, R.id.btn_deploy, R.id.btn_terminal_register, R.id.btn_subject_two_three, R.id.btn_subject_one, R.id.btn_subject_four, R.id.tv_login_version})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.btn_status://状态信息
                Bundle status = new Bundle();
                status.putString(Const.BUNDLE_KEY_PARAM_TYPE, TerminalParameter.APP_PARAM);
                intent = new Intent(this, DeployInfoActivity.class);
                intent.putExtras(status);
                startActivity(intent);

//                Intent intent1  = new Intent();
//                intent1.setClass(this, LivePushActivity.class);
//                startActivity(intent1);
                break;
            case R.id.btn_deploy://配置信息
                Bundle deploy = new Bundle();
                deploy.putString(Const.BUNDLE_KEY_PARAM_TYPE, TerminalParameter.TERMINAL_PARAM);
                intent = new Intent(this, DeployInfoActivity.class);
                intent.putExtras(deploy);
                startActivity(intent);
//                Intent intent1  = new Intent();
//                intent1.setClass(this, LivePushActivity.class);
//                startActivity(intent1);
                break;
            case R.id.btn_terminal_register://终端注册
                intent = new Intent(this, TerminalInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_subject_two_three://科二三登录
                mSubject = Const.TrainPart.TWO;
                gotoLogin();
                break;
            case R.id.btn_subject_one://科一登录
                mSubject = Const.TrainPart.ONE;
                gotoLogin();
                break;
            case R.id.btn_subject_four://科四登录
                mSubject = Const.TrainPart.FOUR;
                gotoLogin();
                break;
            case R.id.tv_login_version:
                if (DeviceUtils.fastFiveClick() || !NetConst.RELEASE_SERVER) {
                    DebugActivity.openDebug(this);
                }
                break;
        }
    }


    /**
     * 登录
     */
    private void gotoLogin() {
        if (PreferenceManager.isRegister()) {

            boolean isProhibitTrain = PreferenceManager.getBoolean(Const.SP_IS_PROHIBIT_TRAIN, false);
            //是否可以训练
            if (!isProhibitTrain) {
                boolean isAuthenticated = TerminalSocketClientManager.getInstance().isAuthenticated();
                if (isAuthenticated) {
                    showLoginType(true);
                } else {
                    TerminalSocketClientManager.getInstance().authenTicate();
                }
            } else {
                //禁止训练
                DialogUtils.showSingleButtonAlertDialog(this, "禁止登录"
                        , PreferenceManager.getString(Const.SP_PROHIBIT_MSG, "")
                        , "确定", NormalAlertDialog.Builder.DIALOG_STYLE_RED
                        , Const.DIALOG_PROHIBIT_TAG, this);
            }
        } else {
            showAlertDialog("未注册终端无法登录，\n请先进行终端注册", Const.DIALOG_DEVICE_UNREGISTER_TAG);
        }
    }

    private void showLoginType(boolean isSign) {
        LoginTypeDialog dialog = new LoginTypeDialog(this);
        dialog.setLoginType(TerminalBaseInfoDaoManager.getInstance().getLoginType());
        dialog.isSign(isSign);
        dialog.setOnLoginTypeClickListener(this);
        dialog.show();
    }

    @Override
    public void onLoginTypeClick(Dialog dialog, View v, short loginType) {
        dialog.dismiss();
        switch (loginType) {
            case Const.LOGIN_TYPE_FACE:
            case Const.LOGIN_TYPE_VERT:
            case Const.LOGIN_TYPE_WX:
                showToast("暂不支持");
                break;
            case Const.LOGIN_TYPE_IDCARD:
                isIdCardReading = true;
                DialogUtils.showProgressBarDialog(this, "读卡中...", this);
                DeviceFactory.hardware.readIDCard(this);
                break;
            case Const.LOGIN_TYPE_APP:
                tell0x0401Transmission(loginType, null);
                break;
            case Const.LOGIN_TYPE_RFID:
                if (Const.QHYC_C103.equals(TerminalApplication.channelModel)) {
                    showReadCardDialog();
                } else {
                    String cardNumber = DeviceFactory.hardware.readIcCard(this);
                    tell0x0401Transmission(loginType, cardNumber);
                }
                break;
        }
    }

    /**
     * 小鹿设备外接刷卡
     */
    public void showReadCardDialog() {
        ReadCardDialog readCardDialog = new ReadCardDialog(this);
        readCardDialog.setOnInputOverListener(this);
        readCardDialog.show();
    }

    @Override
    public void onInputOver(Dialog dialog, String result) {
        dialog.dismiss();
        tell0x0401Transmission(Const.LOGIN_TYPE_RFID, result);
    }

    //提示
    private void showAlertDialog(String content, int tag) {
        DialogUtils.showSingleButtonAlertDialog(this
                , "提示", content
                , "确定", NormalAlertDialog.Builder.DIALOG_STYLE_NORMAL
                , tag, this);
    }

    @Override
    public void onNormalAlertDialogClick(NormalAlertDialog dialog, View view, int btnType) {
        dialog.dismiss();
        switch (btnType) {
            case NormalAlertDialog.NORMAL_ALERT_DIALOG_CLOSE:
            case NormalAlertDialog.NORMAL_ALERT_DIALOG_RIGHT://继续训练
            case NormalAlertDialog.NORMAL_ALERT_DIALOG_LEFT://结束训练
                if (dialog.getTag() == Const.DIALOG_HAS_UNFINISH_TAG) {
                    List<ClassRecord> noFinishedTrain = ClassRecordDaoManager.getInstance().findUnFinishedTwoOrThreeTrain();
                    TwoAndThreeActivity.unusualOpen(this, noFinishedTrain.get(0).get_ID(), btnType == NormalAlertDialog.NORMAL_ALERT_DIALOG_LEFT);
                    finish();
                }
                break;
            case NormalAlertDialog.NORMAL_ALERT_DIALOG_MIDDLE:
                if (dialog.getTag() == Const.PhotoEventType.TEACHE_SIGN_IN) {
                    CameraActivity.startCameraActivity(this,
                            Const.TakePhotoMode.COUNT_DOWN_TIME, 2, Const.PhotoEventType.TEACHE_SIGN_IN
                            , 0, null
                            , mCoachInfo.getName()
                            , Const.CameraChannel.FONT, null, null, false);
                } else if (dialog.getTag() == Const.DIALOG_DEVICE_UNREGISTER_TAG) {
                    TerminalBaseInfo terminalBaseInfo = TerminalBaseInfoDaoManager.getInstance().getTerminalBaseInfo();
                    if (terminalBaseInfo != null) {
                        final Terminal0x0100Request obj = new Terminal0x0100Request();
                        obj.setCityId(terminalBaseInfo.getCityId());
                        obj.setProvinceId(terminalBaseInfo.getProvinceId());
                        obj.setManufactureId(TerminalApplication.channelModel);
                        obj.setDeviceModel(TerminalApplication.channelModel);
                        obj.setDeviceSequence(DeviceFactory.hardware.getSerialNumber(this));
                        obj.setImei(DeviceFactory.getInstance().getHardware().getImei(this));
                        obj.setSignColor((short) terminalBaseInfo.getSignColor());
                        obj.setIdentification(terminalBaseInfo.getIdentification());
                        TerminalSocketClientManager.getInstance().tell(obj, false);
                    } else {
                        showToast("终端信息不完整，尝试重启应用");
                    }
                }
                break;
        }

    }

    /**
     * 读取身份证
     *
     * @param cardEntry
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventReadIDCard(ReadIdCardBean cardEntry) {
        DialogUtils.dismissDialog();
        if (ReadIdCardBean.STATUS_NO_CONNECT == cardEntry.status) {
            showToast("请检查设备连接是否成功");
        } else if (ReadIdCardBean.STATUS_ERROR == cardEntry.status) {
            showToast("请放入身份证");
        } else if (ReadIdCardBean.STATUS_SUCESS == cardEntry.status) {
            isIdCardReading = false;
            tell0x0401Transmission(Const.LOGIN_TYPE_IDCARD, cardEntry.uid);
        }
    }

    /**
     * 终端注册应答
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8100Response(Terminal0x8100Response ox8100) {
        Logger.t("0x8100终端注册").w(ox8100.toString());
        //0：成功；1：车辆已被注册；2：数据库中无该车辆；3：终端已被注册；4：数据库中无该终端。
        switch (ox8100.getResult()) {
            case 0:
                showToast("终端注册成功");
                //保存注册状态
                PreferenceManager.putBoolean(Const.SP_IS_TERMINAL_REGISTER, true);
                showOrHide();
                //保存设备信息
                TerminalBaseInfoDaoManager.getInstance().insertAndUpdateTerminalBaseInfo(ox8100);
                //开始鉴权
                TerminalSocketClientManager.getInstance().authenTicate();
                break;
            case 1:
                showToast("车辆已被注册");
                break;
            case 2:
                showToast("数据库中无该车辆");
                break;
            case 3:
                showToast("终端已被注册");
                break;
            case 4:
                showToast("数据库中无该终端");
                break;
        }
    }

    /**
     * 根据用户身份 发送0x0401 身份认证透传消息
     *
     * @param type       登录方式
     * @param cardNumber 卡号
     */
    private void tell0x0401Transmission(short type, String cardNumber) {
        DialogUtils.showProgressBarDialog(this, R.string.get_user_identity);
        this.loginType = type;
        Terminal0x0401Transmission ox0401 = new Terminal0x0401Transmission();
        ox0401.setType(type);
        ox0401.setUserType(Const.LOGIN_ROLE_COACH);
        if (Const.LOGIN_TYPE_RFID == type || Const.LOGIN_TYPE_IDCARD == type) {
            ox0401.setCardCode(cardNumber);
        }
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0401, false, true));
    }

    /**
     * @param ox8401 身份认证
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8401Transmission(Terminal0x8401Transmission ox8401) {
        DialogUtils.dismissDialog();
        //请求身份认证信息应答
        switch (ox8401.getResult()) {
            case 0:
                switch (loginType) {
                    case Const.LOGIN_TYPE_APP:
                        qrDialog = DialogUtils.showQRDialog(this, new String(ox8401.getContent()), this);
                        if (qrDialog == null) {
                            showToast("二维码获取失败，请重新获取！");
                        }
                        break;
                    case Const.LOGIN_TYPE_IDCARD:
                    case Const.LOGIN_TYPE_RFID:
                        tell0x0402Transmission(new String(ox8401.getContent()));
                        break;
                }
                break;
            case 1:
                showToast("获取信息失败");
                break;
            case 9:
                showToast("其他错误");
                break;
        }
    }

    @Override
    public void onCountDownTimerFinish(CountDownTimer countDownTimer) {
        try {
            if (qrDialog != null && qrDialog.isShowing()) {
                qrDialog.dismiss();
                qrDialog = null;
            }
        } catch (Exception e) {
        }
        tell0x0401Transmission(Const.LOGIN_TYPE_APP, null);
    }


    /**
     * 扫码成功，APP端确认 之后
     * 服务下发教练，学员信息，并获取统一编号
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8702Response(Terminal0x8702Response ox8702) {
        if (qrDialog != null && qrDialog.isShowing()) {
            qrDialog.dismiss();
            qrDialog = null;
        }
        tell0x0402Transmission(ox8702.getCardCode());
    }

    /**
     * 根据用户身份和身份证号获取统一编号
     *
     * @param IDCardNum 身份证号
     */
    public void tell0x0402Transmission(String IDCardNum) {
        DialogUtils.showProgressBarDialog(this, R.string.get_unified_num);
        mCoachInfo = UserInfoDaoManager.getInstance().insertUserInfoOrFind(IDCardNum);
        TransmissionMessageUtil messageUtil = new TransmissionMessageUtil();
        Terminal0x0402Transmission ox0402 = new Terminal0x0402Transmission();
        ox0402.setType((short) 2);
        ox0402.setNo(IDCardNum);
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0402, false, true));
    }

    /**
     * @param ox8402 返回统一编号 0x0402
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8402Transmission(Terminal0x8402Transmission ox8402) {
        //请求教练统一编号信息应答
        short result = ox8402.getResult();
        //0：成功；1：失败（失败时无后续字段）；9：其他错误
        switch (result) {
            case 0:
                String unifiedNum = ox8402.getNo();//统一编号
                mCoachInfo.setUnifiedNum(unifiedNum);
                UserInfoDaoManager.getInstance().update(mCoachInfo);
                Terminal0x0703Request ox0703 = new Terminal0x0703Request();
                ox0703.setUserType(Const.LOGIN_ROLE_COACH);
                ox0703.setUnifiedNum(unifiedNum);
                TerminalSocketClientManager.getInstance().tellWithNeedAuth(ox0703);
                DialogUtils.showProgressBarDialog(this, R.string.get_user_info);
                break;
            case 1:
                DialogUtils.dismissDialog();
                showToast("教练没有统一编号信息");
                break;
            case 9:
                DialogUtils.dismissDialog();
                showToast("其他错误");
                break;
        }
    }

    /**
     * 获取教练员信息
     * 并上报登录
     *
     * @param ox8703 0x8703
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8703Response(Terminal0x8703Response ox8703) {
        DialogUtils.dismissDialog();
        switch (ox8703.getResult()) {
            case 0:
                mCoachInfo.setName(TextUtils.isEmpty(ox8703.getName()) ? "" : ox8703.getName());
                mCoachInfo.setSex(ox8703.getSex());
                mCoachInfo.setPhone(ox8703.getPhone());
                mCoachInfo.setPhotoUrl(ox8703.getPhotoUrl());
                mCoachInfo.setDrivingType(ox8703.getDrivingType());
                UserInfoDaoManager.getInstance().update(mCoachInfo);
                tell0x0101Transmission();
                break;
            case 1:
                showToast(getString(R.string.no_find_info));
                break;
        }
    }

    /**
     * 上报教练员登陆
     */
    private void tell0x0101Transmission() {
        DialogUtils.showProgressBarDialog(this, "教练登录中...");
        Terminal0x0101Transmission ox0101 = new Terminal0x0101Transmission();
        ox0101.setCoachCard(mCoachInfo.getIDCardNum());
        ox0101.setCoachNo(mCoachInfo.getUnifiedNum());
        ox0101.setDrivingType(mCoachInfo.getDrivingType());
        ox0101.setGnss(LocationUtils.getGnssPackage(LocationMgr.getBestLocation()));
        //harisucici 上报监管
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0101, false, true));
        TerminalSocketClientManager_8001.getInstance().tellWithNoAuth(messageUtil.buildTerminal0x0900Request(ox0101, false, true));

    }

    /**
     * 上传照片
     * 照片上传成功，进入相关界面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventUploadImage(AbstractResponse response) {
        int msgId = response.getId();
        if (msgId == 0x900) {
            if (response.getResult() == 0) {
                Logger.t("UploadImage").d("sequence :" + response.getSequence() + "__result:" + response.getResult());
                if (response.getSequence() == sequence) {
                    DialogUtils.dismissDialog();
                    switch (subjectType) {
                        case Const.CLASS_TYPE:
                            showSelectTrainSubjectDialog();
                            break;
                        case Const.CAR_TYPE:
                        case Const.SIMULATE_TYPE:
                            CoachLoginRecord coachLoginRecord = CoachLoginRecordDaoManager.getInstance().insertCoachLoginRecord(mCoachInfo.get_ID(), mSubject);
                            TwoAndThreeActivity.normalOpen(this, coachLoginRecord.get_ID());
                            finish();
                            break;
                    }
                }
            } else {
                DialogUtils.dismissDialog();
                showAlertDialog("照片上传失败，请重试！", Const.PhotoEventType.TEACHE_SIGN_IN);
            }
        }
    }

    /**
     * 展示选择训练项目弹窗
     */
    public void showSelectTrainSubjectDialog() {
        List<TrainProjectEntity> trainProjectsByPart = TrainProjectEntityManager.getInstance().getTrainProjectsByPart(this, mSubject);
        ListDialog listDialog = new ListDialog(this);
        listDialog.setData(trainProjectsByPart);
        listDialog.setOnItemClickListener(this);
        listDialog.show();
    }

    @Override
    public void onItemClick(Dialog dialog, TrainProjectEntity t) {
        dialog.dismiss();
        CoachLoginRecord coachLoginRecord = CoachLoginRecordDaoManager.getInstance().insertCoachLoginRecord(mCoachInfo.get_ID(), mSubject);
        coachLoginRecord.setProjectCode(t.getProjectCode());
        coachLoginRecord.setProjectName(t.getProjectName());
        CoachLoginRecordDaoManager.getInstance().update(coachLoginRecord);
        OneAndFourActivity.startOneAndFourActivity(this, coachLoginRecord.get_ID(), mSubject, t.getProjectCode(), t.getProjectName());
        finish();
    }

    @Override
    public void onCloseClick(Dialog dialog) {

    }

    /**
     * 上报教练员登录应答
     * 收到成功应答 然后拍照
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8101Transmission(Terminal0x8101Transmission ox8101) {
        DialogUtils.dismissDialog();
        //教练扫码登陆应答
        short result = ox8101.getResult();
        switch (result) {
            case 1:
                mCoachInfo.setUserType(UserInfo.USER_COACH);
                mCoachInfo.setUnifiedNum(ox8101.getCoachNo());
                UserInfoDaoManager.getInstance().update(mCoachInfo);
                showToast("教练员登录成功");
                CameraActivity.startCameraActivity(this,
                        Const.TakePhotoMode.COUNT_DOWN_TIME
                        , 2, Const.PhotoEventType.TEACHE_SIGN_IN
                        , 0, null, mCoachInfo.getName()
                        , Const.CameraChannel.FONT, null, null, false);
                break;
            case 2:
                showToast("无效的教练员编号");
                break;
            case 3:
                showToast("准教车型不符");
                break;
            case 9:
                showToast("其他错误");
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventTakePhoto(TakePhotoEntity takePhoto) {
        EventBus.getDefault().removeStickyEvent(takePhoto);
        int photoEventType = takePhoto.photoEventType;
        if (TakePhotoEntity.TAKE_PHOTO_SUCESS == takePhoto.status) {
            ImageInfo imageInfo = TerminalUtils.getImageInfo(takePhoto.photoPath);
            //照片初始化
            Terminal0x0305Transmission transmission = getTerminal0x0305Transmission(imageInfo.imageNo, imageInfo.imageBuffer);
            Terminal0x0900Request req = new TransmissionMessageUtil().buildTerminal0x0900Request(transmission, false, false);
            TerminalSocketClientManager.getInstance().tellWithNeedAuth(req);
            sendToServer(imageInfo.imageBuffer, imageInfo.imageNo);
        } else {
            showAlertDialog("拍照失败请重试！", photoEventType);
        }
    }


    /**
     * 初始化照片信息
     *
     * @param imageNo 图片编号
     * @param buffer  图片二进制
     * @return 0x0305
     */
    private Terminal0x0305Transmission getTerminal0x0305Transmission(String imageNo, byte[] buffer) {
        Terminal0x0305Transmission transmission = new Terminal0x0305Transmission();
        transmission.setImageNo(imageNo);
        transmission.setUserNo(mCoachInfo.getUnifiedNum());
        //1：平台拍照指令后上传自动请求上传；2：平台查询后要求上传；129：终端主动拍照上传；255：停止拍摄并上传图片
        transmission.setUploadType(Const.UploadPhotoType.TERMINAL_UPLOAD);
        transmission.setCameraChannel((short) 0);
        transmission.setSize((short) 2);
        transmission.setEventType((short) Const.PhotoEventType.TEACHE_SIGN_IN);
        transmission.setDataLength(buffer.length);
        transmission.setClassId(BuildDataUtil.getCoachClassId());
        transmission.setGnss(LocationUtils.getGnssPackage(LocationMgr.getBestLocation()));
        transmission.setTrustable((short) 100);
        int packageCount = TerminalUtils.getImagePackageCount(buffer);
        transmission.setPackageCount(packageCount);
        transmission.setAttachementList(TerminalApplication.getTerminalContext().getLocationAttachement());
        return transmission;
    }

    /**
     * 上传照片到服务器
     */
    public void sendToServer(final byte[] newBuffer, final String imgName) {
        DialogUtils.showProgressBarDialog(this, R.string.upload_image);
        ThreadManager.getInstance().getUploadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Terminal0x0306Transmission transmission = new Terminal0x0306Transmission();
                    transmission.setImageNo(imgName);
                    transmission.setContent(newBuffer);
                    Terminal0x0900Request req = messageUtil.buildTerminal0x0900Request(transmission, false, true);
                    TerminalSocketClientManager.getInstance().tellAndSync(req);
                    //tell的流水号
                    sequence = req.getSeq();
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.dismissDialog();
                            showAlertDialog("照片上传失败，请重试！", Const.PhotoEventType.TEACHE_SIGN_IN);
                        }
                    });
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            TerminalSocketClientManager.getInstance().close();
            TerminalSocketClientManager.getInstance().stopSendHead();
            TerminalSocketClientManager_8001.getInstance().close();
            AppManager.getAppManager().AppExit(this, false);
        }
        return true;
    }


    @Override
    public void onDismiss(DialogInterface dialog) {
        if (isIdCardReading) {
            DeviceFactory.hardware.closeSerialPort();
        }
    }
}
